import legacy from "@vitejs/plugin-legacy";
import postCssPxToRem from "postcss-pxtorem";
import { visualizer } from "rollup-plugin-visualizer";
import { defineConfig, loadEnv } from "vite";
import path from "path";
import createVitePlugins from "./vite/plugins";

import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_PORT, VITE_HOST, VITE_STATIC_BASE_URI, VITE_LEGACY_OFF, VITE_VISUALIZER_ONVITE_BUILD_DIST } = env;

  const plugins = [
    createVitePlugins(env, command === "build"),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ];
  const legacyPluginOn = !VITE_LEGACY_OFF || VITE_LEGACY_OFF !== "true";

  if (legacyPluginOn) {
    plugins.push(
      legacy({
        renderLegacyChunks: true,
        targets: ["chrome 49"],
        additionalLegacyPolyfills: ["regenerator-runtime/runtime"], // 面向IE11时需要此插件
      }),
    );
  }
  //if (VITE_VISUALIZER_ON && VITE_VISUALIZER_ON !== 'false') {
  //  // 将 visualizer 插件放到最后的位置
  //  plugins.push(visualizer());
  //}

  return {
    // 部署生产环境和开发环境下的URL。
    // 默认情况下，vite 会假设你的应用是被部署在一个域名的根路径上
    // 例如 https://www.xxx.com/。
    // 如果应用被部署在一个子路径上，需要指定子路径(在.env文件中配置)。
    // 例如，如果你的应用被部署在 https://www.xxx.com/prod/，则设置 VITE_STATIC_BASE_URI='/prod/'。
    base: VITE_STATIC_BASE_URI || "",
    //build: {
    //  outDir: VITE_BUILD_DIST || './dist'
    //},
    assetsInclude: ["**/*.xlsx"], // 添加对 xlsx 文件的支持
    plugins: plugins,
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置路径
        "~": path.resolve(__dirname, "./"),
        // 设置别名
        "@": path.resolve(__dirname, "./src"),
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    // vite 相关配置
    server: {
      port: VITE_PORT || 8082,
      host: VITE_HOST || true,
      open: false,
    },
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: "internal:charset-removal",
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === "charset") {
                  atRule.remove();
                }
              },
            },
          },
          postCssPxToRem({
            rootValue: 1, // 1rem，根据 设计稿宽度/10 进行设置
            propList: ["*"], // 需要转换的属性，这里选择全部都进行转换
          }),
        ],
      },
      //只是全局导入变量
      preprocessorOptions: {
        less: {
          additionalData: `@import "@/assets/styles/config";`,
        },
      },
    },
    build: {
      assetsInlineLimit: 0, // 禁止转base64编码
    },
  };
});
